// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using Microsoft.Extensions.DependencyInjection;
using SnapObjects.Expressions;

namespace SnapObjects.Data
{
    internal class DefaultExpressionEval : IDefaultExpressionEval
    {
        private readonly Type _modelType;
        private readonly IEvaluateExpressionParser _evaluater;
        private readonly ICompileExpressionParser _compiler;

        public DefaultExpressionEval(IServiceProvider provider, Type modelType)
        {
            _modelType = modelType;
            _compiler = provider.GetService<ICompileExpressionParser>();
            _evaluater = provider.GetService<IEvaluateExpressionParser>();
        }

        private ICompileScript Parse(string expression)
        {
            if (_compiler == null)
            {
                throw new NotSupportedException("Pre compiled!");
            }

            var options = new CompileParserOptions(
                expression, SourceKind.Default, _modelType);

            return _compiler.Parse(options);
        }

        public LambdaDelegate Compile(string expression)
        {
            return this.Parse(expression).Compile();
        }

        public object Evaluate(string expression, object model)
        {
            if (_compiler == null)
            {
                throw new NotSupportedException("Real-time calculation!");
            }

            var options = new EvaluateParserOptions(
                expression, SourceKind.Default, model);

            return this.Evaluate(options);
        }

        public object Evaluate(EvaluateParserOptions options)
        {
            if (_compiler == null)
            {
                throw new NotSupportedException("Real-time calculation!");
            }

            return _evaluater.Parse(options);
        }
    }
}
